import { getToken } from '@/utils/token';
import { PlusOutlined } from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd';
import { message, Modal, Upload } from 'antd';
import React, { useMemo, useState } from 'react';

interface ImageUploadProps {
  value?: UploadFile[];
  onChange?: (fileList: UploadFile[]) => void;
  maxCount?: number;
  disabled?: boolean;
}

const ImageUpload: React.FC<ImageUploadProps> = ({
  value = [],
  onChange,
  maxCount = 9,
  disabled = false,
}) => {
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');

  const finalValue = useMemo(() => {
    return value?.map?.((item) => {
      return {
        ...item,
        thumbUrl: item.url,
        status: item?.status ?? 'done',
      };
    });
  }, [value]);

  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    const res = newFileList.map((item) => {
      return {
        ...item,
        url: item.response?.data,
        thumbUrl: item.response?.data,
      };
    });
    onChange?.(res);
  };

  const handlePreview = async (file: UploadFile) => {
    // if (!file.url && !file.preview) {
    //   file.preview = await getBase64(file.originFileObj as File);
    // }
    setPreviewImage(file.url || '');
    setPreviewOpen(true);
    setPreviewTitle(
      file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1),
    );
  };

  const handleRemove = (file: UploadFile) => {
    const newFileList = value.filter((item) => item.uid !== file.uid);
    onChange?.(newFileList);
  };

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传图片</div>
    </div>
  );

  return (
    <>
      <Upload
        action="/datas/files/upload"
        listType="picture-card"
        headers={{
          token: getToken() as string,
        }}
        fileList={finalValue}
        onChange={handleChange}
        onPreview={handlePreview}
        onRemove={handleRemove}
        accept="image/*"
        maxCount={maxCount}
        disabled={disabled}
        beforeUpload={(file) => {
          const isImage = file.type.startsWith('image/');
          if (!isImage) {
            message.error('只能上传图片文件!');
            return false;
          }
          return true;
        }}
      >
        {value.length >= maxCount ? null : uploadButton}
      </Upload>

      <Modal
        open={previewOpen}
        title={previewTitle}
        footer={null}
        onCancel={() => setPreviewOpen(false)}
        width={800}
        centered
      >
        <img alt="preview" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </>
  );
};

// 将文件转换为base64用于预览
// const getBase64 = (file: File): Promise<string> =>
//   new Promise((resolve, reject) => {
//     const reader = new FileReader();
//     reader.readAsDataURL(file);
//     reader.onload = () => resolve(reader.result as string);
//     reader.onerror = error => reject(error);
//   });

export default ImageUpload;
